package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.AddressDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private AddressDao addressDao;

    @Override
    public Result submit(Map map) {
        try {

            //检查是否进行了预约设置
            String orderDate = (String)map.get("orderDate");
            System.out.println(orderDate);
            // 检查 t_ordersetting 表，看当前 日期是否可以预约
            OrderSetting orderSetting1 = orderSettingDao.findByDate1(orderDate);
            System.out.println(orderSetting1);
            if(orderSetting1 == null){
               return new Result(false,MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            }

            //检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
            if(orderSetting1.getNumber() <= orderSetting1.getReservations()){
                return new Result(false,MessageConstant.ORDER_FULL);
            }


            //套餐ID
            System.out.println(map.get("setmealId"));
            String setmealId1 = (String)map.get("setmealId");
            Integer setmealId = Integer.parseInt(setmealId1);

            //检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约，根据手机号是否在数据库中已经存在进行预约
            String telephone = (String) map.get("telephone");
            // 检查 t_member 表，是否有 注册的电话号码
            Member member = orderDao.getByMemberTelephone(telephone);
            System.out.println("member"+member);
            Integer memberId;
            //没有 注册
            if(member == null){

                //   sex ---sex
                String sex = (String) map.get("sex");
                //   idCard---idCard
                String idCard = (String)map.get("idCard");
                //   phoneNumber--telephone
                String phoneNumber = telephone;
                // name
                String name = (String) map.get("name");
                //   regTime  --- new Date()
                Member member1 = new Member(sex,idCard,phoneNumber,name,new Date());
                orderDao.insertToMember(member1);
                memberId = member1.getId();

            }else{
                //检查用户是否重复预约(同一个用户在同一天预约了同一个套餐)，如果是重复预约则无法完成再次预约
                memberId = member.getId();//会员ID
                System.out.println(memberId);
                List<Order> orderList = orderDao.getByMemberIdAndOrderDateAndSetmealId(memberId, DateUtils.parseString2Date(orderDate), setmealId);
                System.out.println(orderList);
                if(orderList != null){
                    return new Result(false,MessageConstant.HAS_ORDERED);
                }
            }
            //进行预约  memberId    telephone    setmealId  orderType  orderDate（String 类型）
            String orderType = (String)map.get("orderType");
            String orderStatus = "未到诊";
            String address = (String) map.get("address");
            //预约人的对象
            Order order = new Order(memberId,DateUtils.parseString2Date(orderDate),orderType,orderStatus,setmealId,address);
            orderDao.insertOrder(order);



            /*根据新增订单id进行中间表的关联*/
            //获取order的id
            Integer orderId = order.getId();
            /*//获取地址信息
            String address1 = order.getAddress();*/
            //根据地址信息查询地址对应的id
            Integer addressId = addressDao.findByAddress(address);
            //调用下面的一个方法
            this.setOrderAddAddress(orderId,addressId);



            //预约成功，更新当日的已预约人数，  orderDate
            int number = orderSetting1.getNumber();
            int reservations = orderSetting1.getReservations();

            //下面三行，因为互联网项目，有可能会发生数据不同步的问题，所以可以不再这里 加一  ，可以在数据库中原先的基础上进行加1
            reservations++;
            OrderSetting orderSetting2 = new OrderSetting(null,DateUtils.parseString2Date(orderDate),reservations);
            orderSettingDao.updateNumberAndReservations(orderSetting2);

            return new Result(true, MessageConstant.ORDER_SUCCESS,order.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "预约失败");
        }
    }

    @Override
    public Result findById(Integer id) {
        try {
            Map map = orderDao.findById(id);
            System.out.println(map);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }

    //每日到诊数
    @Override
    public List<Integer> findOrderStatusCountByMonths(List<String> months) {
        List<Integer> orderStatusCount = new ArrayList<>();
        for (String month : months) {
            String data = month;
            Integer count = orderDao.findVisitsCountByDate(data);
            orderStatusCount.add(count);
        }
        return orderStatusCount;
    }

    //每日未诊数
    @Override
    public List<Integer> findNotOrderStatusCountByMonths(List<String> months) {
        List<Integer> orderStatusCount = new ArrayList<>();
        for (String month : months) {
            String data = month;
            Integer count = orderDao.findNotVisitsCountByDate(data);
            orderStatusCount.add(count);
        }
        return orderStatusCount;
    }

    public void setOrderAddAddress(Integer orderId,Integer addressId){
        //先判断一下上个数据不为空
        if (addressId != null && orderId != null) {
            //创建一个map集合
            Map<String,Integer> map = new HashMap<>();
            //存入key和veiw
            map.put("order_id",orderId);
            map.put("address_id",addressId);
            //调用orderdao的下面方法存入，将两者的id存入第三张表。
            orderDao.setOrderIdAddAddressId(map);
        }
    }
}
